﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Trade.DAL;
using Trade.Model;
using Trade.Controls;

namespace Trade
{
    public partial class FrmPurchase : RayForm
    {
        private Purchase purchase = new Purchase();
        private Product product = new Product();
        private Common common = new Common();
        private DataTable dtDetail = null;
        private BindingSource bs;
        private bool rowChanged = false;
        private Utility.CRUD dataState = Utility.CRUD.None;
        private FrmPurchaseMain purchaseMainForm = null;

        public FrmPurchase()
        {
            InitializeComponent();
        }

        private void PurchaseForm_Load(object sender, EventArgs e)
        {
            txtPurchaseNo.Enabled = false;

            cmbWarehouse.Tag = "H000";
            common.ComboBoxBindingDataSource(cmbWarehouse, "SubjectName", "SubjectId");

            common.VendorComboBoxDataBinding(cmbVendor, "VendorName", "VendorNo");
            common.EmployeeComboBoxDataBinding(cmbBuyer, "ChineseName", "ChineseName");

            if ((Utility.CRUD)this.Tag == Utility.CRUD.Insert)
            {
                txtPurchaseNo.Text = purchase.GenPurchaseNo(DateTime.Now.ToString("yyyyMMdd")).Trim();

                dtDetail = purchase.PurchaseDetailTemplate();

                bs = new BindingSource(this.dtDetail, null);
                dgvPurchaseDetail.DataSource = bs;
                SetDetailDataGridView();
                txtReferenceNo.Focus();

                dtDetail.Rows.Add();
            }
            else
            { 
                purchaseMainForm = (FrmPurchaseMain)this.Owner;
                txtPurchaseNo.Text = purchaseMainForm.dtMaster.Rows[purchaseMainForm.curRowIndex]["PurchaseNo"].ToString();
                txtReferenceNo.Text = purchaseMainForm.dtMaster.Rows[purchaseMainForm.curRowIndex]["ReferenceNo"].ToString();
                cmbVendor.SelectedValue = purchaseMainForm.dtMaster.Rows[purchaseMainForm.curRowIndex]["VendorNo"].ToString();
                cmbWarehouse.SelectedValue = purchaseMainForm.dtMaster.Rows[purchaseMainForm.curRowIndex]["ReceivedWH"].ToString();
                cmbBuyer.SelectedValue = purchaseMainForm.dtMaster.Rows[purchaseMainForm.curRowIndex]["Buyer"].ToString();
                dtpEntryDate.Value = Convert.ToDateTime(purchaseMainForm.dtMaster.Rows[purchaseMainForm.curRowIndex]["EntryDate"]);
                txtRemark.Text = purchaseMainForm.dtMaster.Rows[purchaseMainForm.curRowIndex]["Remark"].ToString();

                dtDetail = purchase.GetPurchaseDetailByNo(txtPurchaseNo.Text.Trim());

                bs = new BindingSource(this.dtDetail, null);
                dgvPurchaseDetail.DataSource = bs;
                SetDetailDataGridView();
                txtPurchaseNo.Focus();
            }
        }

        private void SetDetailDataGridView()
        {
            dgvPurchaseDetail.Columns[0].Width = 100;
            dgvPurchaseDetail.Columns[0].Name = dtDetail.Columns["PurchaseNo"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[0].HeaderText = "进货单号";
            dgvPurchaseDetail.Columns[0].Visible = false;
            dgvPurchaseDetail.Columns[1].Width = 60;
            dgvPurchaseDetail.Columns[1].Name = dtDetail.Columns["LineNo"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[1].HeaderText = "行号";
            dgvPurchaseDetail.Columns[1].ReadOnly = true;
            dgvPurchaseDetail.Columns[2].Width = 100;
            dgvPurchaseDetail.Columns[2].Name = dtDetail.Columns["ProductNo"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[2].HeaderText = "商品编号";
            dgvPurchaseDetail.Columns[3].Width = 150;
            dgvPurchaseDetail.Columns[3].Name = dtDetail.Columns["ProductName"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[3].HeaderText = "商品名称";
            dgvPurchaseDetail.Columns[3].ReadOnly = true;
            dgvPurchaseDetail.Columns[4].Width = 150;
            dgvPurchaseDetail.Columns[4].Name = dtDetail.Columns["ProductSpec"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[4].HeaderText = "商品规格";
            dgvPurchaseDetail.Columns[4].ReadOnly = true;
            //dgvPurchaseDetail.Columns[4].Frozen = true;
            dgvPurchaseDetail.Columns[5].Width = 60;
            dgvPurchaseDetail.Columns[5].Name = dtDetail.Columns["SubjectName"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[5].HeaderText = "单位";
            dgvPurchaseDetail.Columns[6].Width = 60;
            dgvPurchaseDetail.Columns[6].Name = dtDetail.Columns["LotNo"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[6].HeaderText = "批号";
            dgvPurchaseDetail.Columns[7].Width = 80;
            dgvPurchaseDetail.Columns[7].Name = dtDetail.Columns["ProductDate"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[7].HeaderText = "生产日期";
            dgvPurchaseDetail.Columns[8].Width = 80;
            dgvPurchaseDetail.Columns[8].Name = dtDetail.Columns["Qty"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[8].HeaderText = "数量";
            dgvPurchaseDetail.Columns[9].Width = 80;
            dgvPurchaseDetail.Columns[9].Name = dtDetail.Columns["Price"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[9].HeaderText = "单价";
            dgvPurchaseDetail.Columns[10].Width = 100;
            dgvPurchaseDetail.Columns[10].Name = dtDetail.Columns["Amount"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[10].HeaderText = "金额";
            dgvPurchaseDetail.Columns[10].ReadOnly = true;
            dgvPurchaseDetail.Columns[11].Width = 80;
            dgvPurchaseDetail.Columns[11].Name = dtDetail.Columns["DiscountRate"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[11].HeaderText = "折扣%";
            dgvPurchaseDetail.Columns[11].Visible = false;
            dgvPurchaseDetail.Columns[12].Width = 100;
            dgvPurchaseDetail.Columns[12].Name = dtDetail.Columns["DiscountPrice"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[12].HeaderText = "折扣单价";
            dgvPurchaseDetail.Columns[12].Visible = false;
            dgvPurchaseDetail.Columns[13].Width = 100;
            dgvPurchaseDetail.Columns[13].Name = dtDetail.Columns["DiscountAmt"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[13].HeaderText = "折扣金额";
            dgvPurchaseDetail.Columns[13].Visible = false;
            dgvPurchaseDetail.Columns[14].Width = 80;
            dgvPurchaseDetail.Columns[14].Name = dtDetail.Columns["TaxRate"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[14].HeaderText = "税率%";
            dgvPurchaseDetail.Columns[15].Width = 100;
            dgvPurchaseDetail.Columns[15].Name = dtDetail.Columns["TaxAmount"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[15].HeaderText = "税金";
            dgvPurchaseDetail.Columns[15].ReadOnly = true;
            dgvPurchaseDetail.Columns[16].Width = 80;
            dgvPurchaseDetail.Columns[16].Name = dtDetail.Columns["PriceInTax"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[16].HeaderText = "含税单价";
            dgvPurchaseDetail.Columns[17].Width = 100;
            dgvPurchaseDetail.Columns[17].Name = dtDetail.Columns["AmountInTax"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[17].HeaderText = "含税金额";
            dgvPurchaseDetail.Columns[17].ReadOnly = true;
            dgvPurchaseDetail.Columns[18].Width = 80;
            dgvPurchaseDetail.Columns[18].Name = dtDetail.Columns["ValidDate"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[18].HeaderText = "有效期";
            dgvPurchaseDetail.Columns[19].Width = 200;
            dgvPurchaseDetail.Columns[19].Name = dtDetail.Columns["Remark"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[19].HeaderText = "备注";
            dgvPurchaseDetail.Columns[20].Width = 60;
            dgvPurchaseDetail.Columns[20].Name = dtDetail.Columns["RecordId"].ColumnName.ToString();
            dgvPurchaseDetail.Columns[20].HeaderText = "记录ID";
            dgvPurchaseDetail.Columns[20].Visible = false;

            dgvPurchaseDetail.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        //判断DataTable中的Rows的RowState，根据其状态进行相应的操作
        private void HandledDataTable()
        {
            for (int i = 0; i < dtDetail.Rows.Count; i++)
            {
                DataRowState drs = dtDetail.Rows[i].RowState;

                switch (drs)
                {
                    case DataRowState.Modified:
                        break;
                    case DataRowState.Added:
                        break;
                    case DataRowState.Deleted:
                        break;
                }

                if (dtDetail.Rows[i].RowState != DataRowState.Deleted)
                {
                    dtDetail.Rows[i][0].ToString();
                }
                else
                {
                    dtDetail.Rows[i][0, DataRowVersion.Original].ToString();
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            MessageBox.Show(purchase.GenPurchaseNo("20111018"));
        }

        private void bntVendor_Click(object sender, EventArgs e)
        {
            Form parent = this.FindForm();

            ComboPopup popup = new ComboPopup();
            //popup.Location = new Point(txtVendor.Left, txtVendor.Top + txtVendor.Bottom + txtVendor.Height + 3);
            //popup.Location = new Point(txtVendor.Left + txtVendor.Left + 4, txtVendor.Top + txtVendor.Bottom + txtVendor.Height + 3);
            popup.Show();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            MessageBox.Show(DateTime.Now.ToString("yyyyMMdd"));
        }

        private void dgvPurchaseDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //验证编辑的单元格的数据
            DataGridViewCell dgvCell = dgvPurchaseDetail.Rows[e.RowIndex].Cells[e.ColumnIndex];
            int newInteger;

            if (string.IsNullOrEmpty(e.FormattedValue.ToString()) == false)
            {
                switch (dgvPurchaseDetail.Columns[e.ColumnIndex].Name)
                {
                    case "ProductNo":
                        if (product.IsExistProductNo(e.FormattedValue.ToString()) == false)
                        {
                            MessageBox.Show("商品编号 [" + e.FormattedValue.ToString() + "] 不存在！");
                            e.Cancel = true;
                        }
                        break;
                    case "Qty":
                        if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0)
                        {
                            MessageBox.Show("数量不能小于0！");
                            e.Cancel = true;
                        }
                        break;
                    case "Price":
                        if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0)
                        {
                            MessageBox.Show("单价不能小于0！");
                            e.Cancel = true;
                        }
                        break;
                }
            }
        }

        private void dgvPurchaseDetail_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (rowChanged == false)
            {
                return;
            }

            DataGridViewRow dgvRow = dgvPurchaseDetail.Rows[e.RowIndex];

            if (string.IsNullOrEmpty(dgvRow.Cells["ProductNo"].Value.ToString()))
            {
                MessageBox.Show("商品编号不能为空！");
                dgvRow.Cells["ProductNo"].Selected = true;
                e.Cancel = true;
                return;
            }
        }

        private void dgvPurchaseDetail_CellValidated(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvPurchaseDetail_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            rowChanged = true;
        }

        //当光标
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)    //监听回车事件
            {

                //if (this.dgvPurchaseDetail.IsCurrentCellInEditMode)   //如果当前单元格处于编辑模式
                //{
                    if (this.dgvPurchaseDetail.CurrentCell.ColumnIndex == this.dgvPurchaseDetail.ColumnCount - 2 && this.dgvPurchaseDetail.CurrentCell.RowIndex == this.dgvPurchaseDetail.RowCount - 1)   //光标在最后一列
                    {
                        if (!string.IsNullOrEmpty(dgvPurchaseDetail.Rows[dgvPurchaseDetail.CurrentCell.RowIndex].Cells["ProductNo"].Value.ToString()))
                        {
                            dtDetail.Rows.Add();
                            this.dgvPurchaseDetail.CurrentCell = this.dgvPurchaseDetail[1, this.dgvPurchaseDetail.CurrentCell.RowIndex + 1];
                        }
                    }
                //}
            }
            //继续原来base.ProcessCmdKey中的处理
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}
